package com.spence.wsdemo.utils;

import com.spence.wsdemo.entity.WsPrincipal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author spence_xu
 * @date 2020/5/20 16:10
 */
@Slf4j
@Component
public class SocketUtils {

    @Resource
    private SimpMessageSendingOperations messagingTemplate;

    public WsPrincipal getPrincipal(SimpMessageHeaderAccessor headerAccessor) {
        return (WsPrincipal) headerAccessor.getUser();
    }

    /**
     * 给APP指定用户发送消息
     */
    public void sendToUser(String message, String destination, WsPrincipal principal) {
        log.info("send msg {} to {} by subscribe {}", message, principal.getName(), destination);
        messagingTemplate.convertAndSendToUser(principal.getName(), destination, message);
    }
}
